package com.kly.cashmall.utils.system;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;

import com.kly.cashmall.bean.ContactsBean;

/**
 * @author zxp
 * @since 27/10/21
 */
public class ContactsUtils {

    private static final String PHONESTART = "1";
    private static final String AREACODE = "+86";

    public static ContactsBean parseContactsBean(Context context, Uri uri) {

        ContactsBean contactsBean = null;
        try {
            Cursor c = context.getContentResolver().query(uri, null, null, null, null);
            if (c != null && c.moveToFirst()) {
                String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                if (PHONESTART.equalsIgnoreCase(hasPhone)) {
                    Cursor phones = context.getContentResolver()
                            .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);

                    if (phones != null && phones.moveToFirst()) {
                        String cNumber = phones.getString(
                                phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        cNumber = cNumber.replace(AREACODE, "").replace(" ", "").replace("-", "");

                        String nameContact =
                                c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

                        contactsBean = new ContactsBean();
                        contactsBean.mobile = cNumber;
                        contactsBean.name = nameContact;

                        phones.close();
                    }
                    c.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contactsBean;
    }
}
